package com.sk.sourcecircle.activity.mine.act;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Environment;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.dyhdyh.widget.loading.dialog.LoadingDialog;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.tools.PictureFileUtils;
import com.sk.sourcecircle.R;
import com.sk.sourcecircle.adapter.ReleasePictureAdapter;
import com.sk.sourcecircle.base.BaseActivity;
import com.sk.sourcecircle.callback.HandleDataCallBack;
import com.sk.sourcecircle.utils.AppApi;
import com.sk.sourcecircle.utils.HttpAddress;
import com.sk.sourcecircle.utils.MD5;
import com.sk.sourcecircle.utils.MyUtils;
import com.sk.sourcecircle.view.FlowLayout;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by sk on 2017/11/23.
 */

public class FeedBackActivity extends BaseActivity implements HandleDataCallBack, BaseQuickAdapter.OnItemClickListener {
    @BindView(R.id.back)
    ImageView back;
    @BindView(R.id.apply)
    TextView apply;
    @BindView(R.id.flow_ll)
    FlowLayout flowLl;
    @BindView(R.id.tv_content)
    EditText tvContent;
    @BindView(R.id.gird_view)
    RecyclerView girdView;
    @BindView(R.id.ed_phone)
    EditText edPhone;

    private String[] feedArray = new String[]{"闪退", "卡顿问题", "程序错误", "功能建议", "死机问题", "其他"};
    String image;
    List<CheckBox> selectList = new ArrayList<>();
    private List<CheckBox> checkBoxes = new ArrayList<>();
    private LoadingDialog loadingDialog;

    private ReleasePictureAdapter releasePictureAdapter;

    private List<LocalMedia> allList = new ArrayList<>();
    private List<LocalMedia> pictureList = new ArrayList<>();

    private int count = 0;
    private StringBuilder builder;

    @Override
    protected int getContentView() {
        return R.layout.activity_feed_back;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        builder = new StringBuilder();
        loadingDialog = MyUtils.getLoadingDialog(mContext, false);
        allList.add(new LocalMedia());
        girdView.setLayoutManager(new GridLayoutManager(this, 4));
        releasePictureAdapter = new ReleasePictureAdapter(R.layout.item_release_pic, allList);
        girdView.setAdapter(releasePictureAdapter);

        releasePictureAdapter.setOnItemClickListener(this);
        for (int i = 0; i < feedArray.length; i++) {
            View view = LayoutInflater.from(mContext).inflate(R.layout.item_feed_check, flowLl, false);
            CheckBox checkBox = view.findViewById(R.id.checkbox);
            checkBox.setText(feedArray[i]);
            checkBox.setTag(i + 1);
            checkBoxes.add(checkBox);
            flowLl.addView(view);
        }

        for (int i = 0; i < checkBoxes.size(); i++) {
            final int finalI = i;
            checkBoxes.get(i).setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    if (isChecked) {
                        selectList.add(checkBoxes.get(finalI));
                    } else {
                        selectList.remove(checkBoxes.get(finalI));
                    }
                }
            });
        }

        edPhone.setText(MyUtils.getMyInfo(mContext).getPhone());

    }


    private String getReleaseId() {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < selectList.size(); i++) {
            int tag = (int) selectList.get(i).getTag();
            if (i == selectList.size() - 1) {
                sb.append(String.valueOf(tag));
            } else {
                sb.append(String.valueOf(tag)).append(",");
            }
        }
        Log.v("getReleaseId", sb.toString());
        return sb.toString();
    }


    @OnClick({R.id.back, R.id.apply})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.back:
                finish();
                break;
            case R.id.apply:

                if (getReleaseId().length() >= 1) {

                    loadingDialog.show();

                    //发布相册
                    if (pictureList.size() > 0) {
                        for (int i = 0; i < pictureList.size(); i++) {
                            loadingDialog.show();
                            if (pictureList.get(i).isCompressed()) {
                                Bitmap bitmap = BitmapFactory.decodeFile(pictureList.get(i).getCompressPath());
//                            upLoadAppendixImg(new File(pictureList.get(i).getCompressPath()));
                                upLoadAppendixImg(bitmap);
                            } else {
                                Bitmap bitmap = BitmapFactory.decodeFile(pictureList.get(i).getPath());
//                            upLoadAppendixImg(new File(pictureList.get(i).getPath()));
                                upLoadAppendixImg(bitmap);
                            }
                        }
                    } else {
                        loadingDialog.show();
                        AppApi.adviceFeedback(MyUtils.getMobile(mContext), tvContent.getText().toString(), "", getReleaseId(), FeedBackActivity.this, 0, FeedBackActivity.this);
                    }
                    break;
                } else {
                    Toast.makeText(mContext, "请至少选择一个问题类型!", Toast.LENGTH_SHORT).show();
                }


        }
    }


    @Override
    public void handlerSuccessData(String result, int tag) {
        loadingDialog.cancelDialog();
        Toast.makeText(mContext, "反馈成功la ~，感谢您的建议~~", Toast.LENGTH_SHORT).show();
        finish();
    }

    @Override
    public void handlerFailData(String failString, int tag) {
        loadingDialog.cancelDialog();
    }

    @Override
    public void handleErrorData(String error, int tag) {
        loadingDialog.cancelDialog();
    }

    @Override
    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
        if (position == 0) {
            PictureSelector.create(FeedBackActivity.this)
                    .openGallery(PictureMimeType.ofImage())//全部.PictureMimeType.ofAll()、图片.ofImage()、视频.ofVideo()、音频.ofAudio()
                    .maxSelectNum(9)// 最大图片选择数量 int
                    .imageSpanCount(4)// 每行显示个数 int
                    .selectionMode(PictureConfig.MULTIPLE)// 多选 or 单选 PictureConfig.MULTIPLE or PictureConfig.SINGLE
                    .previewImage(true)// 是否可预览图片 true or false
                    .isCamera(true)// 是否显示拍照按钮 true or false
                    .imageFormat(PictureMimeType.PNG)// 拍照保存图片格式后缀,默认jpeg
                    .isZoomAnim(true)// 图片列表点击 缩放效果 默认true
                    .sizeMultiplier(0.5f)// glide 加载图片大小 0~1之间 如设置 .glideOverride()无效
                    .enableCrop(false)// 是否裁剪 true or false
                    .compress(true)// 是否压缩 true or false
                    .compressSavePath(Environment.getExternalStorageDirectory().getPath())//压缩图片保存地址
                    .selectionMedia(pictureList)// 是否传入已选图片 List<LocalMedia> list
                    .previewEggs(true)// 预览图片时 是否增强左右滑动图片体验(图片滑动一半即可看到上一张是否选中) true or false
                    .cropCompressQuality(90)// 裁剪压缩质量 默认90 int
                    .minimumCompressSize(100)// 小于100kb的图片不压缩
                    .synOrAsy(true)//同步true或异步false 压缩 默认同步
                    .forResult(PictureConfig.CHOOSE_REQUEST);//结果回调onActivityResult code
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case PictureConfig.CHOOSE_REQUEST:
                    // 图片选择结果回调
                    List<LocalMedia> selectList = PictureSelector.obtainMultipleResult(data);
                    // 例如 LocalMedia 里面返回三种path
                    // 1.media.getPath(); 为原图path
                    // 2.media.getCutPath();为裁剪后path，需判断media.isCut();是否为true
                    // 3.media.getCompressPath();为压缩后path，需判断media.isCompressed();是否为true
                    // 如果裁剪并压缩了，以取压缩路径为准，因为是先裁剪后压缩的
                    pictureList.clear();
                    pictureList.addAll(selectList);
                    allList.clear();
                    allList.add(new LocalMedia());
                    allList.addAll(pictureList);
                    releasePictureAdapter.notifyDataSetChanged();
                    break;
            }
        }
    }

    private void upLoadAppendixImg(Bitmap bitmap) {
        RequestParams requestParams = new RequestParams(HttpAddress.TestIp + HttpAddress.UploadImage);
        requestParams.addBodyParameter("img_url", MyUtils.bitmapToBase64(bitmap));
        long timeStamp = System.currentTimeMillis();
        requestParams.addBodyParameter("timestamp", String.valueOf(timeStamp));
        requestParams.addBodyParameter("token", MyUtils.getToken(mContext));
        requestParams.addBodyParameter("sign", MD5.md5(timeStamp + "_yuanquan"));
        x.http().post(requestParams, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                Log.v("upLoadAppendixImg", result);
                if (count == pictureList.size() - 1) {
                    clearCache();
                    com.alibaba.fastjson.JSONObject jsonObject = JSON.parseObject(result);
                    String imageUrl = jsonObject.getString("data");
                    builder.append(imageUrl);
                    Log.v("upLoadAppendixImg", builder.toString());
                    AppApi.adviceFeedback(MyUtils.getMobile(mContext), tvContent.getText().toString(), builder.toString(), getReleaseId(), FeedBackActivity.this, 0, FeedBackActivity.this);
                } else {
                    com.alibaba.fastjson.JSONObject jsonObject = JSON.parseObject(result);
                    String imageUrl = jsonObject.getString("data");
                    builder.append(imageUrl).append(",");
                    count++;
                    Bitmap bitmap = BitmapFactory.decodeFile(pictureList.get(0).getPath());
                    upLoadAppendixImg(bitmap);
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Log.v("upLoadAppendixImg", ex.toString());
                loadingDialog.cancelDialog();
            }

            @Override
            public void onCancelled(CancelledException cex) {
                loadingDialog.cancelDialog();
            }

            @Override
            public void onFinished() {

            }
        });
    }

    private void clearCache() {
        PictureFileUtils.deleteCacheDirFile(FeedBackActivity.this);
    }


}
